package com.imau.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imau.common.R;
import com.imau.common.ResultCodeEnum;
import com.imau.entity.Student;
import com.imau.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@Api(tags = "登录验证")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private StudentService studentService;


    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R login(@RequestBody Student student) {

        Map<String, Object> stuMap;

        // 1. 将页面提交的密码password进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(student.getPassword().getBytes());

        // 2. 根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getUsername, student.getUsername());
        Student stu = studentService.getOne(queryWrapper);

        // 3. 如果没有查询则返回登录失败的结果
        if (stu == null) {
            return R.error(ResultCodeEnum.USER_NOT_EXIST);
        }

        // 4. 密码对比，如果不一致则返回登录失败的结果
        if (!stu.getPassword().equals(password)) {
            return R.error(ResultCodeEnum.USER_LOGIN_PASSWORD_ERROR);
        }

        if (stu.getRole()!=1) {
            return R.error(ResultCodeEnum.USER_ACCOUNT_FORBIDDEN);
        }

        StpUtil.login(stu.getId());

        String tokenValue = StpUtil.getTokenInfo().getTokenValue();

        stuMap = JSONObject.parseObject(JSONObject.toJSONString(stu), Map.class);

        stuMap.put("token", tokenValue);

        return R.success(stuMap, ResultCodeEnum.USER_LOGIN_SUCCESS);
    }

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public R logout() {
        StpUtil.logout();
        return R.success(ResultCodeEnum.USER_LOGOUT_SUCCESS);
    }

}
